package com.wenjie.common.unifiedReturn;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.http.converter.json.AbstractJsonHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author wenjie
 * @Description 对controller 返回值不是void和String的处理
 * @date 2024/5/31 13:48
 */
@Slf4j
@ControllerAdvice
@Order(value = 1000)
public class JsonBodyAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private FileUtils fileUtils;

    /**
     * 只处理不返回void的，并且MappingJackson2HttpMessageConverter支持的类型.
     *
     * @param methodParameter 方法参数
     * @param clazz           处理器
     * @return 是否支持
     */
    @Override
    public boolean supports(MethodParameter methodParameter,
                            Class<? extends HttpMessageConverter<?>> clazz) {
        Method method = methodParameter.getMethod();

        //method为空、返回值为void、非JSON，直接跳过
        if (Objects.isNull(method)
                || method.getReturnType().equals(Void.TYPE)
                || method.getReturnType().equals(Result.class)
                || !this.isJsonHttpMessageConverter(clazz)) {
            return false;
        }
        return fileUtils.file(method);
    }

    @Override
    public Object beforeBodyWrite(
            Object body,
            MethodParameter methodParameter,
            MediaType mediaType,
            Class<? extends HttpMessageConverter<?>> clazz,
            ServerHttpRequest serverHttpRequest,
            ServerHttpResponse serverHttpResponse
    ) {
        if (body == null) {
            return Result.success();
        } else if (body instanceof Result) {
            return body;
        } else {
            return Result.success(body);
        }
    }

    /**
     * 判断是否是JSON消息转换器
     *
     * @param clazz
     * @return
     */
    public boolean isJsonHttpMessageConverter(Class<? extends HttpMessageConverter<?>> clazz) {
        return AbstractJsonHttpMessageConverter.class.isAssignableFrom(clazz)
                || AbstractJackson2HttpMessageConverter.class.isAssignableFrom(clazz);
    }
}
